<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\V1\Traits\CouponTrait;
use App\Http\Controllers\Controller;
use App\Models\PointBag;
use App\Models\PointBagLog;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;


class PointBagController extends Controller
{
    use CouponTrait;
    public function buyPointBag(PointBag $pointBag)
    {
        $user = Auth::user();
        if ($user->point < $pointBag->point) {
            return response()->json(['code' => 1001, 'message' => '积分不足购买失败'], 400);
        }

        //计算福袋产出
        $discount_coupon = random_int($pointBag->discount_coupon['min']* 100, $pointBag->discount_coupon['max']* 100) / 100;
        //给用户添加相应折扣的折扣券
        if ($discount_coupon != 0) {
            $this->addCoupon($user, 'discount', '福袋折扣券', Carbon::now()->addDays($pointBag->discount_coupon['expired_at'])->toDateTimeString(), $discount_coupon);
        }

        $random = random_int(0,100);
        $free_coupon = $pointBag->free_coupon['percent']*100 > $random ? true : false;
        //TODO 如果free_coupon为true，则为用户添加免费咖啡券
        $this->addCoupon($user, 'free', '福袋咖啡券', Carbon::now()->addDays($pointBag->free_coupon['expired_at'])->toDateTimeString());

        $growing_coffee = random_int($pointBag->growing_coffee['min']* 100, $pointBag->growing_coffee['max']* 100) / 100;
        //给用户添加相应成长咖啡
        $userGrowingCoffee = $user->growing_coffee;
        if (($userGrowingCoffee + $growing_coffee) >= 1) {
            $user->growing_coffee = 1;
            $user->save();
        } else {
            $user->growing_coffee = ($userGrowingCoffee + $growing_coffee);
            $user->save();
        }

        //添加用户的开启福袋记录
        $pointBagLog = PointBagLog::create([
            'user_id' => $user->id,
            'name' => $pointBag->name,
            'image' => $pointBag->image,
            'growing_coffee' => $growing_coffee,
            'free_coupon' => $free_coupon,
            'discount_coupon' => $discount_coupon
        ]);
        return response()->json(['code' => 1, 'data' => $pointBagLog]);
    }
}
